class Solution {
public:
    int m, n;
    vector<vector<int>> memo;
    int ret = 0;
    int longestIncreasingPath(vector<vector<int>>& matrix) {
        m = matrix.size(), n = matrix[0].size();
        memo = vector<vector<int>>(m + 1, vector<int>(n + 1, -1));
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                ret = max(ret, dfs(i, j, matrix));
            }
        }
        return ret;
    }
    int dx[4] = {-1, 1, 0, 0};
    int dy[4] = {0, 0, -1, 1};
    int dfs(int i, int j, vector<vector<int>>& matrix) {
        if (memo[i][j] != -1) {
            return memo[i][j];
        }
        int count = 1;
        for (int k = 0; k < 4; k++) {
            int x = i + dx[k], y = j + dy[k];
            if (x >= 0 && y >= 0 && x < m && y < n &&
                matrix[i][j] < matrix[x][y]) {
                count = max(count, dfs(x, y, matrix) + 1); // 长度加一
            }
        }
        memo[i][j] = count;
        return count;
    }
};